clear

clear
use "$saveoutputs/ProdQ_new_klme_2lags"

tempfile params
save `params', replace

use "$working/prowess_wits_estimation_qonly_klme.dta", clear

merge m:1 nic_08_2dig using `params'
drop _merge

tabulate nic_08_2dig, sort

***Drop the single product firms that are non-comparable- i.e., missing energy and quantity data
keep if q_s!=. &  energy_intensity!=.

merge m:1 co_code1 year using "$working/first_last_years.dta"
keep if _merge==3
drop _merge

sort product_id year
xtset product_id year
bys co_code1 year: egen nprod = count(co_code1)
tsfill, full
sort product_id year
gen N = missing(L.co_code1)
gen D = missing(f.co_code1)

replace N = . if first_year == 1
replace D = . if last_year == 1

drop if missing(co_code1)

drop cleaned_number_prod
bysort co_code1 year: generate cleaned_number_prods = _N

tabulate cleaned_number_prods

gen omega_j= q_s - beta_l_hat_q * (l + ln_shares) - beta_k_hat_q* ( k + ln_shares) - beta_m_hat_q * (m + ln_shares) - beta_e_hat_q*(e + ln_shares) ///
- beta_lk_hat_q*I_sq - beta_km_hat_q*I_sq_km - beta_lm_hat_q*I_sq_lm - beta_le_hat_q*I_sq_le - beta_ke_hat_q*I_sq_ke - beta_me_hat_q*I_sq_me  
	
egen firm_prod = group(up12 co_code1)
egen firm_year =  group(co_code1 year)

ivreghdfe q_s (ln_price = omega_j), absorb(firm_prod firm_year) first cluster(co_code1)

generate sample0 = e(sample)
keep if sample0 == 1


preserve
	bysort co_code1 year: generate count_thing = _n
	keep if count_thing==1
	keep co_code1 year
	save "$working/Demand_TFPQIV_Qklme_2lags_sampleFS", replace
restore			


preserve
	keep co_code1 year product_name5
	isid co_code1 year product_name5
	save "$working/Demand_TFPQIV_Qklme_2lags_sampleFS_prod", replace
restore

generate sigma_hat= _b[ln_price]	

replace nic_08_2dig = "all"
contract nic_08_2dig sigma_hat 
		
rename _freq Observations
		
local spec = "$spec"
save "$working/D_TFPQIV_Qklme_2lags", replace

collapse (mean) sigma_hat (sum) Observations

generate bs = 0

save "$BS_fold/bs_D_TFPQIV_Qklme_2lags", replace

